package com.wans.ssq.run;

import com.wans.common.redis.RedisPrefix;
import com.wans.model.common.PaginationParam;
import com.wans.ssq.service.SSQService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;

@Component
@Slf4j
public class StartupCacheInitializer implements CommandLineRunner {

    private final SSQService ssqService;
    private final List<Integer> pageSizes = Arrays.asList(10, 30, 50, 100);

    // 构造函数注入依赖
    public StartupCacheInitializer(SSQService ssqService) {
        this.ssqService = ssqService;
    }

    @Override
    @Async   // 异步调用
    public void run(String... args) {
        clearCache();


        // 项目启动完成后执行
        preloadCache();

        log.info("关键数据已缓存完毕");
    }


    public void clearCache() {
        ssqService.clearCache();
    }

    public void preloadCache() {
        for (int pageSize : pageSizes) {
            for (int page = 1; page <= 10; page++) {
                preloadPage(page, pageSize);
            }
        }
        log.info("双色球历史记录前10页缓存加载完成(4种分页大小)");
    }

    private void preloadPage(int page, int pageSize) {
        try {
            PaginationParam paginationCache = new PaginationParam();
            paginationCache.setCurrentPage(page);
            paginationCache.setPageSize(pageSize);

            // 调用service方法触发缓存
            ssqService.cacheHistory(paginationCache);
            log.info("预加载缓存成功, page={}, size={}", page, pageSize);
        } catch (Exception e) {
            log.error("预加载缓存失败, page={}, size={}", page, pageSize, e);
        }
    }
}